package com.zqwh.storemonitor.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

import com.videogo.exception.BaseException;
import com.videogo.openapi.EzvizAPI;
import com.zqwh.storemonitor.Config;
import com.zqwh.storemonitor.R;
import com.zqwh.storemonitor.domain.ShopWatcher;
import com.zqwh.storemonitor.ezviz.SdkInitParams;
import com.zqwh.storemonitor.ezviz.SdkInitTool;
import com.zqwh.storemonitor.ezviz.ServerAreasEnum;
import com.zqwh.storemonitor.model.WatcherModel;
import com.zqwh.storemonitor.service.NotificationService;
import com.zqwh.yj.sdk.utils.LogUtils;
import com.zqwh.yj.sdk.utils.SharePreferencesUtils;
import com.zqwh.yj.sdk.utils.StringUtils;
import com.zqwh.yj.sdk.utils.ToastUtils;
import com.zqwh.yj.sdk.utils.httpRequest.RetrofitSingleton;
import com.zqwh.yj.sdk.utils.httpRequest.subscribers.NetCallback;

import static com.zqwh.storemonitor.StoreMonitorApplication.getOpenSDK;
import static com.zqwh.storemonitor.StoreMonitorApplication.sGeTuiCid;
import static com.zqwh.storemonitor.StoreMonitorApplication.sShopWatcher;

public class FlashActivity extends AppCompatActivity {

    private WatcherModel watcherModel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_flash);
        watcherModel = new WatcherModel(this);
        RetrofitSingleton.setShowNetworkDetail(true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getToken();
    }

    private void getToken() {
        watcherModel.getAccessToken(new NetCallback<String>() {
            @Override
            public void onSuccess(String token) {
                Config.AccessToekn = token;
                initPlayer();
                jumpReady();
            }

            @Override
            public void onError(String msg) {
                ToastUtils.showLongToast(FlashActivity.this, "获取token失败");
            }
        });
    }

    private void jumpReady() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                final String account = SharePreferencesUtils.readStringSharedPreferences(FlashActivity.this,"ACCOUNT");
                final String pwd = SharePreferencesUtils.readStringSharedPreferences(FlashActivity.this,"PWD");

                if (StringUtils.areNotEmpty(account, pwd)){
                    watcherModel.login(account, pwd, new NetCallback<ShopWatcher>() {
                        @Override
                        public void onSuccess(final ShopWatcher shopWatcher) {
                            watcherModel.setGeTuiCid(shopWatcher.getShopWatcherId(), sGeTuiCid, new NetCallback<Object>() {

                                @Override
                                public void onSuccess(Object o) {
                                    SharePreferencesUtils.writeStringSharedPreferences(FlashActivity.this,"ACCOUNT", account);
                                    SharePreferencesUtils.writeStringSharedPreferences(FlashActivity.this,"PWD", pwd);
                                    sShopWatcher = shopWatcher;
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                        if (!Settings.canDrawOverlays(FlashActivity.this)){
                                            getOverlayPermission();
                                            return;
                                        }
                                    }
                                    startService(new Intent(FlashActivity.this, NotificationService.class));
                                    jumpToStoreListActivity();
                                }

                                @Override
                                public void onError(String msg) {

                                }
                            });
                        }

                        @Override
                        public void onError(String msg) {
                            ToastUtils.showLongToast(FlashActivity.this, msg);
                        }
                    });
                }else {
                    jumpToLoginActivity();
                }
            }
        }, 1000);
    }

    private void getOverlayPermission(){
        if (Build.VERSION.SDK_INT >= 23) { // Android6.0及以后需要动态申请权限
            if (!Settings.canDrawOverlays(this)) {
                //启动Activity让用户授权
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, 1010);
            } else {
                // 弹出悬浮窗
            }
        } else {
            // 弹出悬浮窗
        }
    }

    private void jumpToLoginActivity() {
        startActivity(new Intent(this, LoginActivity.class));
        finish();
    }

    private void jumpToStoreListActivity() {
        if (EzvizAPI.getInstance().isLogin()) {
            startActivity(new Intent(this, StoreListActivity.class));
            finish();
        }else{
            getOpenSDK().openLoginPage();
        }
    }

    private void initPlayer() {
        SdkInitParams sdkInitParams = SdkInitParams.createBy(ServerAreasEnum.ASIA_CHINA);
        sdkInitParams.appKey = Config.APPKEY;
        sdkInitParams.accessToken = Config.AccessToekn;
        SdkInitTool.initSdk(getApplication(), sdkInitParams);
        EzvizAPI.getInstance().setServerUrl(ServerAreasEnum.ASIA_CHINA.openApiServer, ServerAreasEnum.ASIA_CHINA.openAuthApiServer);
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (checkAppKeyAndAccessToken()){
                    LogUtils.logout("AppKey和AccessToken有效");
                    SdkInitParams sdkInitParams = SdkInitParams.createBy(ServerAreasEnum.ASIA_CHINA);
                }else {
                    LogUtils.error("AppKey和AccessToken无效");
                }
            }
        }).start();
    }
    /**
     * 通过调用服务接口判断AppKey和AccessToken且有效
     * @return 是否依旧有效
     */
    private boolean checkAppKeyAndAccessToken() {
        boolean isValid = false;
        try {
            getOpenSDK().getDeviceList(0, 1);
            isValid = true;
        } catch (BaseException e) {
            e.printStackTrace();
            LogUtils.error("Error code is " + e.getErrorCode());
            int errCode = e.getErrorCode();
            String errMsg;
            switch (errCode){
                case 400031:
                    errMsg = getApplicationContext().getString(R.string.tip_of_bad_net);
                    break;
                default:
                    errMsg = getApplicationContext().getString(R.string.login_expire);
                    break;
            }
        }
        return isValid;
    }
}
